<script setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { User, Message, Check } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 当前步骤
const activeStep = ref(0)

// 表单数据
const forgotForm = reactive({
  username: '',
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const verifyFormRef = ref(null)
const resetFormRef = ref(null)

// 验证密码
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== forgotForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

// 账户验证规则
const verifyRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 重置密码规则
const resetRules = reactive({
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ]
})

// 验证码计时器
const countdown = ref(0)
const timer = ref(null)

// 获取验证码
const getVerificationCode = async () => {
  await verifyFormRef.value.validate((valid) => {
    if (valid) {
      countdown.value = 60
      timer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer.value)
        }
      }, 1000)
      
      // 这里应该调用发送验证码的API
      ElMessage.success('验证码已发送到您的邮箱')
    }
  })
}

// 验证账户信息
const verifyAccount = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate((valid) => {
    if (valid) {
      // 实际应用中应该调用API验证账户信息
      activeStep.value = 1
    }
  })
}

// 重置密码
const resetPassword = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate((valid) => {
    if (valid) {
      // 实际应用中应该调用API重置密码
      ElMessage.success('密码重置成功')
      router.push('/login')
    }
  })
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<template>
  <div class="forgot-container">
    <div class="forgot-box">
      <div class="forgot-header">
        <h2>找回密码</h2>
        <p>重置您的账号密码</p>
      </div>
      
      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" class="steps">
        <el-step title="账户验证"></el-step>
        <el-step title="重置密码"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      
      <!-- 第一步：账户验证 -->
      <div v-if="activeStep === 0">
        <el-form 
          ref="verifyFormRef"
          :model="forgotForm" 
          :rules="verifyRules" 
          label-position="top"
          class="forgot-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="forgotForm.username" 
              placeholder="请输入用户名"
            >
              <template #prefix>
                <el-icon><user /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="forgotForm.email" 
              placeholder="请输入注册时的邮箱地址"
            >
              <template #prefix>
                <el-icon><message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="forgot-button"
              @click="verifyAccount(verifyFormRef)"
            >
              下一步
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 第二步：重置密码 -->
      <div v-else-if="activeStep === 1">
        <el-form 
          ref="resetFormRef"
          :model="forgotForm" 
          :rules="resetRules" 
          label-position="top"
          class="forgot-form"
        >
          <el-form-item label="验证码" prop="verificationCode">
            <div class="verification-code">
              <el-input 
                v-model="forgotForm.verificationCode" 
                placeholder="请输入验证码"
              ></el-input>
              <el-button 
                type="primary" 
                :disabled="countdown > 0"
                @click="getVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="forgotForm.newPassword" 
              type="password" 
              placeholder="请输入新密码"
              show-password
            ></el-input>
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="forgotForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入新密码"
              show-password
            ></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="forgot-button"
              @click="resetPassword(resetFormRef)"
            >
              重置密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 第三步：完成 -->
      <div v-else class="success-step">
        <el-result
          icon="success"
          title="密码重置成功"
          sub-title="您的密码已经成功重置，请使用新密码登录"
        >
          <template #extra>
            <el-button type="primary" @click="goToLogin">返回登录</el-button>
          </template>
        </el-result>
      </div>
      
      <div class="login-link" v-if="activeStep !== 2">
        <el-link type="primary" @click="goToLogin">返回登录</el-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.forgot-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.forgot-box {
  width: 450px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.forgot-header {
  text-align: center;
  margin-bottom: 20px;
}

.forgot-header h2 {
  margin: 0 0 10px;
  font-size: 24px;
  color: #303133;
}

.forgot-header p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.steps {
  margin: 20px 0 30px;
}

.forgot-form {
  margin-top: 20px;
}

.verification-code {
  display: flex;
  gap: 10px;
}

.verification-code .el-input {
  flex: 1;
}

.forgot-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.login-link {
  margin-top: 20px;
  text-align: center;
}

.success-step {
  margin: 30px 0;
}
</style> 